const _path = require('path')
const fs = require('fs-extra')
const yaml = require('js-yaml')
const rd = require('rd')
const Config = require('./config')

function readConfig (path) {
  const fileContent = fs.readFileSync(`config/${path}.yaml`, 'utf8')
  return yaml.safeLoad(fileContent)
}

function resolvePath (fullpath) {
  let relativePath = _path.relative(base, fullpath)
  return relativePath.replace(/\.yaml$/, '')
}

const finalConfig = {}
let defaultConfig = {}
if (fs.existsSync('config/default.yaml')) {
  defaultConfig = readConfig('default')
}
const base = _path.resolve('config')

rd.eachFileFilterSync(base, /\.yaml$/, function (filepath) {
  const path = resolvePath(filepath)
  if (path === 'default') {
    return
  } else {
    try {
      let pathConfig = readConfig(path)
      pathConfig = Object.assign({}, defaultConfig, pathConfig)
      finalConfig[path] = new Config(path, pathConfig)
    } catch (err) {
      if (err instanceof yaml.YAMLException) {
        console.log(err)
        finalConfig[path] = { error: 'YAML语法错误' }
      } else {
        throw err
      }
    }
  }
})

module.exports = finalConfig
